package com.cloudcross.ssp.web.advertiser.main.ad.report;

import com.cloudcross.ssp.base.dao.GenericIBatisDao;
import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.Config;
import com.cloudcross.ssp.common.utils.DoublePreciseCompute;
import com.cloudcross.ssp.common.utils.HttpClienUtil;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.AdGroup;
import com.cloudcross.ssp.model.Dimension;
import com.cloudcross.ssp.model.Order;
import com.cloudcross.ssp.model.rpt.BannerRpt;
import com.cloudcross.ssp.model.rpt.JsAdRpt;
import com.cloudcross.ssp.model.rpt.LocationRpt;
import com.cloudcross.ssp.model.rpt.OrderRpt;
import com.cloudcross.ssp.model.rpt.OsRpt;
import com.cloudcross.ssp.model.rpt.RealReport;
import com.cloudcross.ssp.model.rpt.Report;
import com.cloudcross.ssp.service.IAdGroupService;
import com.cloudcross.ssp.service.IDimensionService;
import com.cloudcross.ssp.service.IOrderService;
import com.cloudcross.ssp.service.IRptBannerService;
import com.cloudcross.ssp.service.IRptJsAdService;
import com.cloudcross.ssp.service.IRptLocationService;
import com.cloudcross.ssp.service.IRptOrderHourService;
import com.cloudcross.ssp.service.IRptOrderService;
import com.cloudcross.ssp.service.IRptOsService;
import com.cloudcross.ssp.service.impl.ObjectBase;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 需求方广告主表报表
 * @author  wuqiang.du
 */
@Controller
@RequestMapping("/advertiser/main/ad/report/advertiser-report")
public class AdvertiserReportController extends SimpleController {

    @Autowired
    private IDimensionService dimensionService;
    @Autowired
    private FreemarkerTemplateProcessor templateProcessor;
    @Autowired
    private GenericIBatisDao iBatisDao;
    @Autowired
    private IAdGroupService adGroupService;
    @Autowired
    private IRptLocationService rptLocationService;
    @Autowired
    private IRptOsService rptOsService;
    @Autowired
    private IRptBannerService rptBannerService;
    @Autowired
    private IRptOrderService rptOrderService;
    @Autowired
    private IRptJsAdService rptJsAdService;
    @Autowired
    Config config;
    @Autowired
    private IRptOrderHourService rptOrderHourService;
    @Autowired
    private IOrderService orderService;

    /**
     * 总体报表  t_rpt_banner
     *
     * @param model
     * @param paramMap
     * @param page
     * @return
     */
    @RequestMapping
    public String index(Model model, @RequestParam HashMap<String, Object> paramMap,
                        @RequestParam(defaultValue = "1") int page) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermater(paramMap, condition);
        int totalRow = this.rptBannerService.queryBannerCountByCondition(condition);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<BannerRpt> reportList = this.rptBannerService.queryBannerDataByConditon(condition, pager);

        Report reports = this.rptBannerService.queryBannerTotalByCondition(condition);
        if (reports == null) {
            reports = new Report();
        }
        if (reports.getShows() == 0) {
            for (BannerRpt bannerRpt : reportList) {
                bannerRpt.setEcpm(0.0);
            }
            reports.setEcpms(0.0);
        } else {
            for (BannerRpt bannerRpt : reportList) {
                bannerRpt.setEcpm(DoublePreciseCompute.div(bannerRpt.getConsume() * 1000d, bannerRpt.getShow()));
            }
            reports.setEcpms(DoublePreciseCompute.div(reports.getConsumes() * 1000d, reports.getShows()));
        }
        model.addAttribute("reports", reports);
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("reportList", reportList);
        return index;
    }

    /**
     * 总体报表导出
     *
     * @param response
     * @param paramMap
     */
    @RequestMapping("/bannerExcel")
    public void exportBannerToExcel(HttpServletResponse response, @RequestParam Map<String, Object> paramMap) {
        Map<String, Object> condition = new HashMap<String, Object>();
        Account account = getLoginUser();
        //处理前端传过来的参数
        super.initPatermaterExcel(paramMap, condition);

        //选择维度
        Integer dimensionId = null;
        String dimensionName = "请选择维度";
        //选择了维度
        if (null != paramMap.get("selecteddimensionId") && !"".equals(paramMap.get("selecteddimensionId"))
                && -1 != Long.parseLong((String) paramMap.get("selecteddimensionId"))) {
            dimensionId = Integer.parseInt((String) paramMap.get("selecteddimensionId"));
            Map<String, Object> map = getDimensionByPK(dimensionId);
            condition.put("dimensionStr", map.get("dimensionStr"));
            dimensionName = (String) map.get("dimensionName");
            paramMap.put("dimensionLength", map.get("dimensionLength"));
            paramMap.put("dimensionTarget", map.get("dimensionTarget"));
        } else {
            //没选择维度
            //是否有默认的维度
            HashMap<String, Object> dimensionmap = dimensionService.selectDimensionIdBydefault(account.getId());
            //有默认值
            if (dimensionmap.get("num") != null && !"0".equals(dimensionmap.get("num").toString())) {
                dimensionId = (Integer) dimensionmap.get("id");
                Map<String, Object> map = getDimensionByPK(dimensionId);
                condition.put("dimensionStr", map.get("dimensionStr"));
                dimensionName = (String) map.get("dimensionName");
                paramMap.put("dimensionLength", map.get("dimensionLength"));
                paramMap.put("dimensionTarget", map.get("dimensionTarget"));
            } else {
                //没有默认值，设置日期为默认值
                condition.put("dimensionStr", "date");
                paramMap.put("dimensionLength", null);
                paramMap.put("dimensionTarget", null);
            }
        }
        paramMap.put("selecteddimensionId", dimensionId);
        paramMap.put("selecteddimensionName", dimensionName);

        List<BannerRpt> reportList = this.rptBannerService.queryBannerDataByConditon(condition, null);

        Report reports = this.rptBannerService.queryBannerTotalByCondition(condition);
        if (reports == null) {
            reports = new Report();
        }
        paramMap.put("reports", reports);
        //显示的列
        paramMap.put("impression", null);//曝光
        paramMap.put("click", null);//点击
        paramMap.put("consume", null);//花费
        if (null != paramMap.get("checkItems") || !"".equals(paramMap.get("checkItems"))) {
            String[] checkItems = paramMap.get("checkItems").toString().split(",");
            for (int i = 0; i < checkItems.length; i++) {
                if (paramMap.containsKey(checkItems[i])) {
                    paramMap.put(checkItems[i], checkItems[i]);
                }
            }
        }

        response.reset();
        //Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8  
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        //设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "bannerreport" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //需要对excel的列和行的总数进行指定
        int column = 15;
        paramMap.put("reportList", reportList);
        paramMap.put("column", column);
        paramMap.put("dataSize", (reportList.size() + 100));

        String excelTemplate = templateProcessor.processTemplate("excel/rpt/bannerreport.ftl", paramMap);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelTemplate);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 地域报表 修改人：Andy 修改时间：2017.03.23 t_rpt_location
     *
     * @param model
     * @param paramMap
     * @param page
     * @return
     */
    @RequestMapping("/regionReport")
    public String regionReport(Model model, @RequestParam HashMap<String, Object> paramMap,
                               @RequestParam(defaultValue = "1") int page) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermater(paramMap, condition);

        int totalRow = this.rptLocationService.queryLocationCountByCondition(condition);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<LocationRpt> reportList = this.rptLocationService.queryLocationDataByCondition(condition, pager);

        Report reports = this.rptLocationService.queryLocationTotalByCondition(condition);

        if (reports == null) {
            reports = new Report();
        }

        if (reports.getShows() == 0) {
            for (LocationRpt locRpt : reportList) {
                locRpt.setShowRate(0.00);
            }
        } else {
            for (LocationRpt locRpt : reportList) {
                locRpt.setShowRate(DoublePreciseCompute.div(locRpt.getShow() * 100.00, reports.getShows()));
            }

        }
        model.addAttribute("reports", reports);
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("reportList", reportList);
        return page("regionReport");
    }

    /**
     * 区域报表导出
     *
     * @param paramMap
     * @param response
     */
    @RequestMapping("/regionExcel")
    public void exportRegionToExcel(@RequestParam HashMap<String, Object> paramMap, HttpServletResponse response) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermaterExcel(paramMap, condition);

        List<LocationRpt> reportList = this.rptLocationService.queryLocationDataByCondition(condition, null);

        Report reports = this.rptLocationService.queryLocationTotalByCondition(condition);

        if (reports == null) {
            reports = new Report();
        }

        if (reports.getShows() == 0) {
            for (LocationRpt locRpt : reportList) {
                locRpt.setShowRate(0.00);
            }
        } else {
            for (LocationRpt locRpt : reportList) {
                locRpt.setShowRate(DoublePreciseCompute.div(locRpt.getShow() * 100.00, reports.getShows()));
            }

        }

        response.reset();
        //Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8  
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        //设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "regionreport" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //需要对excel的列和行的总数进行指定
        int column = 15;
        paramMap.put("reports", reports);
        paramMap.put("reportList", reportList);
        paramMap.put("column", column);
        paramMap.put("dataSize", (reportList.size() + 100));

        String excelTemplate = templateProcessor.processTemplate("excel/rpt/regionreport.ftl", paramMap);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelTemplate);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 系统报表 修改人：Andy 修改时间：2017.03.23 t_rpt_os
     *
     * @param model
     * @param paramMap
     * @param page
     * @return
     */
    @RequestMapping("/osReport")
    public String osReport(Model model, @RequestParam HashMap<String, Object> paramMap,
                           @RequestParam(defaultValue = "1") int page) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermater(paramMap, condition);
        int totalRow = this.rptOsService.queryOsCountByCondition(condition);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<OsRpt> reportList = this.rptOsService.queryOsDataByCondition(condition, pager);

        Report reports = this.rptOsService.queryOsTotalByCondition(condition);

        if (reports == null) {
            reports = new Report();
        }

        if (reports.getShows() == 0) {
            for (OsRpt osRpt : reportList) {
                osRpt.setShowRate(0.00);
            }
        } else {
            for (OsRpt osRpt : reportList) {
                osRpt.setShowRate(DoublePreciseCompute.div(osRpt.getShow() * 100.00, reports.getShows()));
            }

        }
        model.addAttribute("reports", reports);
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("reportList", reportList);
        return page("osReport");
    }

    /**
     * 区域报表导出
     *
     * @param paramMap
     * @param response
     */
    @RequestMapping("/osExcel")
    public void exportOsToExcel(@RequestParam HashMap<String, Object> paramMap, HttpServletResponse response) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermaterExcel(paramMap, condition);

        List<OsRpt> reportList = this.rptOsService.queryOsDataByCondition(condition, null);

        Report reports = this.rptOsService.queryOsTotalByCondition(condition);

        if (reports == null) {
            reports = new Report();
        }

        if (reports.getShows() == 0) {
            for (OsRpt osRpt : reportList) {
                osRpt.setShowRate(0.00);
            }
        } else {
            for (OsRpt osRpt : reportList) {
                osRpt.setShowRate(DoublePreciseCompute.div(osRpt.getShow() * 100.00, reports.getShows()));
            }

        }

        response.reset();
        //Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8  
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        //设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "osreport" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //需要对excel的列和行的总数进行指定
        int column = 15;
        paramMap.put("reports", reports);
        paramMap.put("reportList", reportList);
        paramMap.put("column", column);
        paramMap.put("dataSize", (reportList.size() + 100));

        String excelTemplate = templateProcessor.processTemplate("excel/rpt/osreport.ftl", paramMap);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelTemplate);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 订单报表 修改人：Andy 修改时间：2017.03.23 t_rpt_order
     *
     * @param model
     * @param paramMap
     * @param page
     * @return
     */
    @RequestMapping("/orderReport")
    public String orderReport(Model model, @RequestParam HashMap<String, Object> paramMap,
                              @RequestParam(defaultValue = "1") int page) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermater(paramMap, condition);
        int totalRow = this.rptOrderService.queryOrderCountByCondition(condition);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<OrderRpt> reportList = this.rptOrderService.queryOrderDateByConditon(condition, pager);

        Report reports = this.rptOrderService.queryOrderTotalByCondition(condition);

        if (reports == null) {
            reports = new Report();
        }

        if (reports.getShows() == 0) {
            for (OrderRpt orderRpt : reportList) {
                orderRpt.setShowRate(0.00);
            }
        } else {
            for (OrderRpt orderRpt : reportList) {
                orderRpt.setShowRate(DoublePreciseCompute.div(orderRpt.getShow() * 100.00, reports.getShows()));
            }

        }
        model.addAttribute("reports", reports);
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("reportList", reportList);
        return page("orderReport");
    }

    /**
     * 订单报表导出
     *
     * @param paramMap
     * @param response
     */
    @RequestMapping("/orderExcel")
    public void exportOrderToExcel(@RequestParam HashMap<String, Object> paramMap, HttpServletResponse response) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermaterExcel(paramMap, condition);

        List<OrderRpt> reportList = this.rptOrderService.queryOrderDateByConditon(condition, null);

        Report reports = this.rptOrderService.queryOrderTotalByCondition(condition);

        if (reports == null) {
            reports = new Report();
        }

        if (reports.getShows() == 0) {
            for (OrderRpt orderRpt : reportList) {
                orderRpt.setShowRate(0.00);
            }
        } else {
            for (OrderRpt orderRpt : reportList) {
                orderRpt.setShowRate(DoublePreciseCompute.div(orderRpt.getShow() * 100.00, reports.getShows()));
            }

        }

        response.reset();
        //Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8  
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        //设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "orderreport" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //需要对excel的列和行的总数进行指定
        int column = 15;
        paramMap.put("reports", reports);
        paramMap.put("reportList", reportList);
        paramMap.put("column", column);
        paramMap.put("dataSize", (reportList.size() + 100));

        String excelTemplate = templateProcessor.processTemplate("excel/rpt/orderreport.ftl", paramMap);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelTemplate);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 维度管理
     */
    //带分页的维度管理list页面    
    @RequestMapping("/dimension")
    public String queryDimensionList(Model model, @RequestParam HashMap<String, Object> paramMap,
                                     @RequestParam(defaultValue = "1") int page) {
        //将当前登录账户ID放入Map中
        paramMap.put("accountId", getLoginUser().getId());
        //查询满足条件的维度记录总数
        int totalRow = dimensionService.countByParams(paramMap);
        //分页信息
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        //带分页的维度记录
        List<Dimension> dimensionList = dimensionService.findByParams(paramMap, pager);

        //model.addAllAttributes(paramMap);
        //将查询结构放入model中，传到前台
        model.addAttribute("pager", pager);
        model.addAttribute("dimensionList", dimensionList);

        return page("dimension");
    }

    //增加维度页面
    @RequestMapping("/create")
    public String create(Model model) {
        model.addAttribute("accountId", getLoginUser().getId());
        return page("create");
    }

    //编辑维度
    @RequestMapping("/edit")
    public String edit(Model model, @RequestParam long id) {
        //根据id查询维度。
        Dimension dimension = dimensionService.findById(id);
        //获取维度方案（以“-”间隔，如“A-B-C”）
        String content = dimension.getContent();
        List<String> alllist = new ArrayList<String>();
        List<String> list = new ArrayList<String>();
        String[] allType = {"广告主", "订单", "策略", "创意", "日期"};
        for (int i = 0; i < allType.length; i++) {
            alllist.add(allType[i]);//保存维度的所有方案
        }
        if (content != null && !"".equals(content)) {
            //将组合维度方案拆分成
            String[] contentArr = content.split("-");
            for (int j = 0; j < contentArr.length; j++) {
                if (alllist.contains(contentArr[j])) {
                    list.add(contentArr[j]);//已选的维度方案
                    alllist.remove(contentArr[j]);//移除已选的维度方案，最终剩下未选的维度方案
                }
            }
        }
        model.addAttribute("accountId", getLoginUser().getId());
        model.addAttribute("dimensionTypeList", list);
        model.addAttribute("notdimensionTypeList", alllist);
        model.addAttribute("dimension", dimension);
        return page("edit");
    }

    //判断名称或类型是否存在
    @RequestMapping("/isExist")
    @ResponseBody
    public String isExist(@ModelAttribute("form") Dimension dimension) {
        String success = "";

        //添加或修改前判断name或content是否已存在
        String name = dimension.getName();
        String content = dimension.getContent();
        Long accountId = getLoginUser().getId();
        List<Dimension> nameList = queryDimensionByNameAndAccountId(name, accountId);
        List<Dimension> contentList = queryDimensionByContentAndAccountId(content, accountId);

        //修改后根据ID来更新当前记录
        //dimensionService.edit(dimension);
        //修改页面和添加页面公用按钮，用ID来区分是添加还是修改
        if (dimension.getId() == null) {//id在数据库中自增长，新增的时候ID为null还没有生成  
            if (nameList.size() > 0) {//维度名称已存在
                success = "YES";
                return success;
            }
            if (contentList.size() > 0) {//维度方案已存在
                success = "YES";
                return success;
            }
            success = "NO";
        } else {//修改保存
            //修改前的维度记录
            Dimension dimensioned = dimensionService.findById(dimension.getId());
            //只修改了name
            if (!dimensioned.getName().equals(dimension.getName())
                    && dimensioned.getContent().equals(dimension.getContent())) {
                //判断name是否存在
                if (nameList.size() > 0) {//维度名称已存在
                    success = "YES";
                } else {//存在
                    success = "NO";//不存在
                }
            } else if (dimensioned.getName().equals(dimension.getName())
                    && !dimensioned.getContent().equals(dimension.getContent())) {
                //只修改了维度方案
                //判断维度方案是否存在
                if (contentList.size() > 0) {
                    success = "YES";//维度方案已存在
                } else {
                    success = "NO";
                }
            } else if (!dimensioned.getName().equals(dimension.getName())
                    && !dimensioned.getContent().equals(dimension.getContent())) {
                //维度名称，方案都修改
                if (nameList.size() > 0) {
                    success = "YES";//维度名称存在
                    return success;
                }
                if (contentList.size() > 0) {
                    success = "YES";//维度方案存在
                    return success;
                }
                success = "NO";//不存在
            } else {//没做任何修改
                success = "NO";
            }

        }
        return success;
    }

    //维度新增或修改页面保存功能
    @RequestMapping("/save")
    public String save(@ModelAttribute("form") Dimension dimension) {
        //修改页面和添加页面公用按钮，用ID来区分是添加还是修改
        if (dimension.getId() == null) {//id在数据库中自增长，新增的时候ID为null还没有生成  
            dimensionService.add(dimension);
        } else {//修改保存
            dimensionService.edit(dimension);
        }
        return redirect(page("dimension"));
    }

    private List<Dimension> queryDimensionByNameAndAccountId(String name, Long accountId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", name);
        map.put("accountId", accountId);
        return iBatisDao.getList("dimensionSqlMapper.queryDimensionByNameAndAccountId", map);
    }

    private List<Dimension> queryDimensionByContentAndAccountId(String content, Long accountId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("content", content);
        map.put("accountId", accountId);
        return iBatisDao.getList("dimensionSqlMapper.queryDimensionByContentAndAccountId", map);
    }

    //删除
    @RequestMapping("/delete")
    public @ResponseBody
    String delete(Long[] id) {
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        if (ArrayUtils.isNotEmpty(id)) {
            paramMap.put("idList", id);
            dimensionService.deleteById(paramMap);
        }
        return OK;
    }

    //维度管理---下拉框的值  
    @RequestMapping("/dimensionlist")
    public @ResponseBody
    List<Dimension> dimensionlist(Model model, @RequestParam HashMap<String, Object> paramMap,
                                  @RequestParam(defaultValue = "1") int page) {
        Account account = getLoginUser();
        paramMap.put("accountId", account.getId());
        List<Dimension> dimensionList = dimensionService.findByParams(paramMap, null);
        return dimensionList;
    }

    //修改默认值
    @RequestMapping("/updateDimensionDefault")
    public @ResponseBody
    String updateDimensionDefault(@RequestParam long dimensionId) {
        Dimension dimension = this.dimensionService.findById(dimensionId);
        dimensionService.updateDimensionDefault(dimension);
        return OK;
    }

    //维度管理  
    public List<HashMap<String, Object>> getDimensionById(@RequestParam long dimensionId) {
        List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        Dimension dimension = dimensionService.findById(dimensionId);
        String content = dimension.getContent();
        if (content != null && !"".equals(content)) {
            String[] contentArr = content.split("-");
            String dimensionStr = "";
            for (int i = 0; i < contentArr.length; i++) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("dimension", contentArr[i]);
                map.put("dimensionTarget", getDimensionType(contentArr[i]));
                dimensionStr += getDimensionType(contentArr[i]) + ",";
                if (i == contentArr.length - 1 && dimensionStr != "") {
                    dimensionStr = dimensionStr.substring(0, dimensionStr.length() - 1);
                    map.put("dimensionStr", dimensionStr);
                }
                list.add(map);
            }

        }
        return list;
    }

    public String getDimensionType(String dimension) {
        String type = "";
        if (dimension.equals("广告主")) {
            type = "advertiserName";
        } else if (dimension.equals("订单")) {
            type = "orderName";
        } else if (dimension.equals("策略")) {
            type = "adgroupName";
        } else if (dimension.equals("创意")) {
            type = "bannerName";
        } else if (dimension.equals("日期")) {
            type = "date";
        }
        return type;
    }

    /**
     * 根据维度ID获取获取对应维度的分组字段组成的字符串
     *
     * @param id 维度的主键
     * @return
     */
    private Map<String, Object> getDimensionByPK(long id) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = null;
        Map<String, Object> condition = new HashMap<String, Object>();
        String dimensionStr = "";
        Dimension dimension = dimensionService.findById(id);
        String content = dimension.getContent();
        String dimensionName = dimension.getName();
        int size = 0;
        Map<String, Object> columnMap = new HashMap<String, Object>();
        if (null != content && !"".equals(content)) {
            String[] contentStr = content.split("-");
            size = contentStr.length;
            for (int i = 0; i < size - 1; i++) {
                map = new HashMap<String, Object>();
                dimensionStr = dimensionStr + getDimensionType(contentStr[i]) + ",";
                map.put("dimensionTarget", getDimensionType(contentStr[i]));
                map.put("dimension", contentStr[i]);
                columnMap.put(getDimensionType(contentStr[i]), getDimensionType(contentStr[i]));
                list.add(map);
            }
            map = new HashMap<String, Object>();
            dimensionStr = dimensionStr + getDimensionType(contentStr[size - 1]);
            map.put("dimension", contentStr[size - 1]);
            map.put("dimensionTarget", getDimensionType(contentStr[size - 1]));
            columnMap.put(getDimensionType(contentStr[size - 1]), getDimensionType(contentStr[size - 1]));
            list.add(map);
        }
        condition.put("dimensionStr", dimensionStr.trim());
        condition.put("dimensionName", dimensionName);
        condition.put("dimensionLength", size);
        condition.put("dimensionTarget", list);
        condition.put("columnMap", columnMap);
        return condition;
    }

    /**
     * http://dsp.adinall.com/cmd=3&adgroups=all
     *
     * @param model
     * @param paramMap
     * @param page
     * @return
     */
    @RequestMapping("/adgroupRealReport")
    public String adgroupRealReport(Model model, @RequestParam HashMap<String, Object> paramMap,
                                    HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        Account users = (Account) session.getAttribute("userSession");
        String url = getAdgroupRealReportUrl();
        long advertiserId = users.getAdvertiserId();
        if (advertiserId > 0) {
            url = url + "&advertiser=" + advertiserId;
        }
        long agentId = users.getAgentId();
        if (agentId > 0) {
            url = url + "&agent=" + agentId;
        }
        String jsonString = HttpClienUtil.postJson(url, "");
        List<RealReport> reportList = new ArrayList<RealReport>();
        if (jsonString != null && !"null".equals(jsonString)) {
            JSONArray array = JSONArray.fromObject(jsonString);
            reportList = JSONArray.toList(array, new RealReport(), new JsonConfig());
        }
        for (RealReport rr : reportList) {
            AdGroup adgroup = this.adGroupService.findById(rr.getId());
            if (adgroup != null) {
                rr.setOrderId(adgroup.getOrderId());
                rr.setName(adgroup.getAdGroupName());
                Order order = orderService.findById(adgroup.getOrderId());
                rr.setOrderName(order.getName());
            }
        }
        model.addAttribute("reportList", reportList);
        return page("adgroupRealReport");
    }

    private String getAdgroupRealReportUrl() {
        return this.config.getAdgroupRealReport();
    }

    /**
     * 广告位报表
     *
     * @param model
     * @param paramMap
     * @param page
     * @return
     */
    @RequestMapping("/jsAdReport")
    public String jsAdReport(Model model, @RequestParam HashMap<String, Object> paramMap,
                             @RequestParam(defaultValue = "1") int page) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermater(paramMap, condition);
        int totalRow = this.rptJsAdService.queryJsAdCountByCondition(condition);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<JsAdRpt> reportList = this.rptJsAdService.queryJsAdDataByCondition(condition, pager);
        Report reports = this.rptJsAdService.queryJsAdTotalByCondition(condition);
        if (reports == null) {
            reports = new Report();
        }
        if (reports.getShows() == 0) {
            for (JsAdRpt jsadRpt : reportList) {
                jsadRpt.setShowRate(0.00);
            }
            reports.setEcpms(0.0);
        } else {
            for (JsAdRpt jsadRpt : reportList) {
                jsadRpt.setShowRate(DoublePreciseCompute.div(jsadRpt.getShow() * 100.00, reports.getShows()));
            }
            reports.setEcpms(DoublePreciseCompute.div(reports.getConsumes() / 1000d, reports.getShows()));
        }
        model.addAttribute("reports", reports);
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("reportList", reportList);
        return page("jsadReport");
    }

    /**
     * app广告位报表
     *
     * @param model
     * @param paramMap
     * @param page
     * @return
     */
    @RequestMapping("/appAdReport")
    public String appAdReport(Model model, @RequestParam HashMap<String, Object> paramMap,
                              @RequestParam(defaultValue = "1") int page) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermater(paramMap, condition);
        int totalRow = this.rptJsAdService.queryAppAdCountByCondition(condition);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<JsAdRpt> reportList = this.rptJsAdService.queryAppAdDataByCondition(condition, pager);
        Report reports = this.rptJsAdService.queryAppAdTotalByCondition(condition);
        if (reports == null) {
            reports = new Report();
        }
        //曝光占比
        if (reports.getShows() == 0) {
            for (JsAdRpt jsadRpt : reportList) {
                jsadRpt.setShowRate(0.00);
            }
            reports.setEcpms(0.0);
        } else {
            for (JsAdRpt jsadRpt : reportList) {
                jsadRpt.setShowRate(DoublePreciseCompute.div(jsadRpt.getShow() * 100.00, reports.getShows()));
            }
            reports.setEcpms(DoublePreciseCompute.div(reports.getConsumes() / 1000d, reports.getShows()));
        }
        model.addAttribute("reports", reports);
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("reportList", reportList);
        return page("appAdReport");
    }

    @RequestMapping("/exportAppReportExcel")
    public void exportAppReportExcel(HttpServletResponse response, @RequestParam Map<String, Object> paramMap) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermaterExcel(paramMap, condition);
        //没有默认值，设置日期为默认值
        List<JsAdRpt> reportList = this.rptJsAdService.queryAppAdDataByCondition(condition, null);
        Report reports = this.rptJsAdService.queryAppAdTotalByCondition(condition);
        if (reports == null) {
            reports = new Report();
        }
        if (reports.getShows() == 0) {
            for (JsAdRpt jsadRpt : reportList) {
                jsadRpt.setShowRate(0.00);
            }
            reports.setEcpms(0.0);
        } else {
            for (JsAdRpt jsadRpt : reportList) {
                jsadRpt.setShowRate(DoublePreciseCompute.div(jsadRpt.getShow() * 100.00, reports.getShows()));
            }
            reports.setEcpms(DoublePreciseCompute.div(reports.getConsumes() / 1000d, reports.getShows()));
        }
        //显示的列
        response.reset();
        //Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        //设置excel文件名称
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "appReport" + format.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //需要对excel的列和行的总数进行指定
        int column = 15;
        paramMap.put("reports", reports);
        paramMap.put("reportList", reportList);
        paramMap.put("column", column);
        paramMap.put("dataSize", (reportList.size() + 100));
        String excelTemplate = templateProcessor.processTemplate("excel/rpt/appadreport.ftl", paramMap);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelTemplate);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/exportPcReportExcel")
    public void exportPcReportExcel(HttpServletResponse response, @RequestParam Map<String, Object> paramMap) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermaterExcel(paramMap, condition);
        //没有默认值，设置日期为默认值
        List<JsAdRpt> reportList = this.rptJsAdService.queryJsAdDataByCondition(condition, null);
        Report reports = this.rptJsAdService.queryJsAdTotalByCondition(condition);
        if (reports == null) {
            reports = new Report();
        }
        if (reports.getShows() == 0) {
            for (JsAdRpt jsadRpt : reportList) {
                jsadRpt.setShowRate(0.00);
            }
            reports.setEcpms(0.0);
        } else {
            for (JsAdRpt jsadRpt : reportList) {
                jsadRpt.setShowRate(DoublePreciseCompute.div(jsadRpt.getShow() * 100.00, reports.getShows()));
            }
            reports.setEcpms(DoublePreciseCompute.div(reports.getConsumes() / 1000d, reports.getShows()));
        }
        //显示的列
        response.reset();
        //Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        //设置excel文件名称
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "pcReport" + format.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //需要对excel的列和行的总数进行指定
        int column = 15;
        paramMap.put("reports", reports);
        paramMap.put("reportList", reportList);
        paramMap.put("column", column);
        paramMap.put("dataSize", (reportList.size() + 100));
        String excelTemplate = templateProcessor.processTemplate("excel/rpt/jsadreport.ftl", paramMap);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelTemplate);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param model
     * @param paramMap
     * @param page
     * @return
     */
    @RequestMapping("/orderHourReport")
    public String orderHourReport(Model model, @RequestParam HashMap<String, Object> paramMap,
                                  @RequestParam(defaultValue = "1") int page) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermater(paramMap, condition);
        int totalRow = this.rptOrderHourService.queryOrderHourCountByCondition(condition);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<OrderRpt> reportList = this.rptOrderHourService.queryOrderHourDataByCondition(condition, pager);
        Report reports = this.rptOrderHourService.queryOrderHourTotalByCondition(condition);
        if (reports == null) {
            reports = new Report();
        }
        //对比订单汇总表
        Report orderReport = this.rptOrderService.queryOrderTotalByCondition(condition);
        if (orderReport == null) {
            orderReport = new Report();
        }
        if (orderReport.getConsumes() > reports.getConsumes()) {
            reportList = ObjectBase.compareRptOrderValue(orderReport, reports, reportList);
            model.addAttribute("reports", orderReport);
        } else {
            model.addAttribute("reports", reports);
        }
        if (reports.getShows() == 0) {
            for (OrderRpt locRpt : reportList) {
                locRpt.setShowRate(0.00);
            }
        } else {
            for (OrderRpt locRpt : reportList) {
                locRpt.setShowRate(DoublePreciseCompute.div(locRpt.getShow() * 100.00, reports.getShows()));
            }
        }
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("reportList", reportList);
        return page("orderHourReport");
    }

    /**
     * 区域报表导出
     *
     * @param paramMap
     * @param response
     */
    @RequestMapping("/orderHourExcel")
    public void exportOrderHourToExcel(@RequestParam HashMap<String, Object> paramMap, HttpServletResponse response) {
        Map<String, Object> condition = new HashMap<String, Object>();
        //处理前端传过来的参数
        super.initPatermaterExcel(paramMap, condition);
        List<OrderRpt> reportList = this.rptOrderHourService.queryOrderHourDataByCondition(condition, null);
        Report reports = this.rptOrderHourService.queryOrderHourTotalByCondition(condition);
        if (reports == null) {
            reports = new Report();
        }
        //对比订单汇总表
        Report orderReport = this.rptOrderService.queryOrderTotalByCondition(condition);
        if (orderReport == null) {
            orderReport = new Report();
        }
        if (orderReport.getConsumes() > reports.getConsumes()) {
            reportList = ObjectBase.compareRptOrderValue(orderReport, reports, reportList);
            paramMap.put("reports", orderReport);
        } else {
            paramMap.put("reports", reports);
        }
        if (reports.getShows() == 0) {
            for (OrderRpt locRpt : reportList) {
                locRpt.setShowRate(0.00);
            }
        } else {
            for (OrderRpt locRpt : reportList) {
                locRpt.setShowRate(DoublePreciseCompute.div(locRpt.getShow() * 100.00, reports.getShows()));
            }
        }
        response.reset();
        //Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8  
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        //设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "orderhourreport" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //需要对excel的列和行的总数进行指定
        int column = 15;
        paramMap.put("reportList", reportList);
        paramMap.put("column", column);
        paramMap.put("dataSize", (reportList.size() + 100));

        String excelTemplate = templateProcessor.processTemplate("excel/rpt/orderhourreport.ftl", paramMap);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelTemplate);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
